import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button, Spin, Empty } from 'antd';
import { ArrowLeftOutlined, SearchOutlined } from '@ant-design/icons';
import { productAPI, categoryAPI } from '../../services/api';
import { addToBrowseHistory } from '../../utils/storage';
import { message } from '../../utils/message';
import './CategoryProducts.css';

const CategoryProducts = () => {
  const { categoryId } = useParams();
  const navigate = useNavigate();
  const [products, setProducts] = useState([]);
  const [category, setCategory] = useState(null);
  const [loading, setLoading] = useState(true);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);

  useEffect(() => {
    loadCategoryInfo();
    loadProducts(1);
  }, [categoryId]);

  const loadCategoryInfo = async () => {
    try {
      const response = await categoryAPI.getCategoryDetail(categoryId);
      if (response.success) {
        setCategory(response.data);
      }
    } catch (error) {
      console.error('加载分类信息失败:', error);
    }
  };

  const loadProducts = async (pageNum = 1) => {
    setLoading(true);
    try {
      const response = await productAPI.getProducts({
        categoryId: parseInt(categoryId),
        page: pageNum,
        pageSize: 10,
        includeInactive: false // 前台只显示上架商品
      });
      
      if (response.success) {
        const newProducts = response.data.list;
        if (pageNum === 1) {
          setProducts(newProducts);
        } else {
          setProducts(prev => [...prev, ...newProducts]);
        }
        setHasMore(newProducts.length === 10);
        setPage(pageNum);
      }
    } catch (error) {
      message.error('加载商品失败');
    } finally {
      setLoading(false);
    }
  };

  const loadMore = () => {
    if (hasMore && !loading) {
      loadProducts(page + 1);
    }
  };

  const handleProductClick = (product) => {
    addToBrowseHistory(product);
    navigate(`/app/product/${product.id}`);
  };

  // 滚动监听
  useEffect(() => {
    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
      if (scrollTop + clientHeight >= scrollHeight - 100) {
        loadMore();
      }
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [hasMore, loading, page]);

  if (loading && products.length === 0) {
    return (
      <div className="category-products-loading">
        <div className="category-header">
          <Button 
            type="text" 
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate(-1)}
          />
          <span className="header-title">商品分类</span>
        </div>
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Spin size="large" />
        </div>
      </div>
    );
  }

  return (
    <div className="category-products-page">
      {/* 头部导航 */}
      <div className="category-header">
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
        />
        <span className="header-title">{category?.name || '商品分类'}</span>
        <Button 
          type="text" 
          icon={<SearchOutlined />}
          onClick={() => navigate('/app/search')}
        />
      </div>

      {/* 分类描述 */}
      {category && (
        <div className="category-info">
          <div className="category-banner">
            <div className="category-icon-large">{category.icon}</div>
            <div className="category-details">
              <h2 className="category-name">{category.name}</h2>
              <p className="category-desc">{category.description || '精选好物，品质保证'}</p>
              <div className="product-count">共 {products.length} 件商品</div>
            </div>
          </div>
        </div>
      )}

      {/* 商品列表 */}
      {products.length === 0 && !loading ? (
        <div style={{ padding: '40px 16px', textAlign: 'center' }}>
          <Empty 
            description="该分类下暂无商品"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
          <Button 
            type="primary" 
            onClick={() => navigate('/app')}
            style={{ marginTop: '16px' }}
          >
            去首页看看
          </Button>
        </div>
      ) : (
        <div className="products-grid">
          {products.map(product => (
            <div 
              key={product.id} 
              className="product-card"
              onClick={() => handleProductClick(product)}
            >
              <img 
                src={product.images[0]} 
                alt={product.name}
                className="product-image"
              />
              <div className="product-info">
                <div className="product-name">{product.name}</div>
                <div className="product-price">¥{product.price}</div>
                {product.originalPrice && product.originalPrice > product.price && (
                  <div className="product-original-price">¥{product.originalPrice}</div>
                )}
                <div className="product-sales">已售 {product.sales || 0}+</div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 加载更多 */}
      {loading && products.length > 0 && (
        <div className="loading-more">
          <Spin size="small" /> 加载中...
        </div>
      )}

      {/* 没有更多 */}
      {!hasMore && products.length > 0 && (
        <div className="no-more">
          没有更多商品了~
        </div>
      )}
    </div>
  );
};

export default CategoryProducts; 